package com.czp.infosharingplatformapp.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;

@Aspect
@Component
public class LoggingAspect {

    private final HttpServletRequest request;
    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    public LoggingAspect(HttpServletRequest request) {
        this.request = request;
    }

    // 在 Controller 层的所有方法执行前记录日志
    @Before("execution(* com.czp.infosharingplatformapp.controller..*(..))")
    public void logBeforeController(JoinPoint joinPoint) {
        // 获取请求信息
        String requestUrl = request.getRequestURI();
        String method = request.getMethod();
        String ipAddress = request.getRemoteAddr();

        logger.info("=========================================");
        logger.info("请求 URL: {}", requestUrl);
        logger.info("HTTP 方法: {}", method);
        logger.info("IP 地址: {}", ipAddress);
        logger.info("调用方法: {}", joinPoint.getSignature().toShortString());
        logger.info("=========================================");
    }

    // 在方法成功返回结果后记录日志
    @AfterReturning(pointcut = "execution(* com.czp.infosharingplatformapp.controller..*(..))", returning = "result")
    public void logAfterController(JoinPoint joinPoint, Object result) {
        logger.info("=========================================");
        logger.info("执行方法: {}", joinPoint.getSignature().toShortString());
        logger.info("返回结果: {}", result);
        logger.info("=========================================");
    }
}